package cn.edu.niit.studyspace.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.litepal.crud.DataSupport;

import java.util.List;

import cn.edu.niit.studyspace.R;
import cn.edu.niit.studyspace.application.MyApplication;
import cn.edu.niit.studyspace.bean.User;

public class LoginActivity extends AppCompatActivity {
    EditText etUsername;
    EditText etPassword;
    CheckBox cbRememberPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //初始化组件
        initComponent();
    }

    private void initComponent() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        cbRememberPassword = findViewById(R.id.cb_remember_password);
        getRememberMsg();//查看是否有之前的登陆信息
    }

    public void login(View view) {
        //校验用户名和密码
        User user = checkLoginPermission(etUsername.getText().toString(), etPassword.getText().toString());
        if (user != null) {
            Intent intent = new Intent(this, MainActivity.class);
            //将user对象存入自定义application中
            MyApplication myApplication = (MyApplication) getApplication();
            myApplication.setCurrentUser(user);
            startActivity(new Intent(intent));
            Toast.makeText(this, "登陆成功！欢迎： " + user.getNickname(), Toast.LENGTH_SHORT).show();
            rememberMsg(user.getUsername(), user.getPassword());
            finish();
        }
    }

    public void register(View view) {
        startActivity(new Intent(this, RegisterActivity.class));
    }

    private User checkLoginPermission(String username, String password) {
        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
            return null;
        }

        List<User> users = DataSupport.select()
                .where("username = '" + username+"'")
                .find(User.class);

        if (users.size() == 0) {
            Toast.makeText(this, "用户名不存在", Toast.LENGTH_SHORT).show();
            return null;
        }

        User user = users.get(0);
        if (!user.getPassword().equals(password)) {
            Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            return null;
        }
        return user;
    }

    /**
     * 存储用户信息至SharedPreferences
     * 警告：这个方法对于存放用户的重要个人信息来说并不安全，仅仅演示SharedPreferences的用法
     *
     * @param username
     * @param password
     */
    private void rememberMsg(String username, String password) {
        SharedPreferences sharedPreferences = getSharedPreferences("rem_user", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("username", username);
        if (cbRememberPassword.isChecked()) {
            editor.putString("password", password);
            editor.putString("checked", "true");
            editor.apply();
        } else {
            editor.putString("checked", "false");
            editor.apply();
        }
    }

    /**
     * 获取存放的用户信息，如果存在，则填充进edittext
     * 也可以做成自动登录。
     */
    private void getRememberMsg() {
        SharedPreferences sharedPreferences = getSharedPreferences("rem_user", MODE_PRIVATE);
        String username = sharedPreferences.getString("username", null);
        String password = sharedPreferences.getString("password", null);
        String checked = sharedPreferences.getString("checked", "false");
        if (username != null) {
            etUsername.setText(username);
        }
        if (password != null && checked.equals("true")) {
            etPassword.setText(password);
            cbRememberPassword.setChecked(true);
        }
    }
}
